package com.example.roomdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import com.example.roomdemo.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding mBinding;
    private EditText mEtAge,mEtName;
    private List<Student> studentList = new ArrayList<>();
    private StudentAdapter mAdapter;
    private StudentViewModel mViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        mViewModel = new ViewModelProvider(this).get(StudentViewModel.class);


        mViewModel.getStudentList().observe(this, new Observer<List<Student>>() {
            @Override
            public void onChanged(List<Student> students) {
                Log.d("aaaa", "数据刷新了");
                studentList.clear();
                studentList.addAll(students);
                mAdapter.notifyDataSetChanged();
            }
        });

        mEtAge = mBinding.editAge;
        mEtName = mBinding.editName;

        mBinding.add.setOnClickListener(v->{
            String age = mEtAge.getText().toString();
            String name = mEtName.getText().toString();
            new Thread(() -> {
                mViewModel.insert(new Student(name,age));

                runOnUiThread(() -> {
                    mEtAge.setText("");
                    mEtName.setText("");
                });
            }).start();
        });

        mBinding.update.setOnClickListener(v->{
            mViewModel.update();
        });

        initRecycler();
    }

    private void initRecycler() {
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mAdapter = new StudentAdapter(this, studentList);
        mBinding.recyclerview.setAdapter(mAdapter);
        mAdapter.setonItemClickListener(student -> {
            mViewModel.delete(student);
        });
    }
}